Imports System.Data.SqlClient

'--- Created By : Priyabrata
'--- Created On : 28-Sep-2010

Public Class frmNurseNote
    Public blnAdd As Boolean, blnEdit As Boolean, blnDelete As Boolean
    Dim mstrMode As String
    Dim mlngRecordID As Long
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnCancelDisplay As Boolean
    Dim VisitId As Integer
    Dim dtCharge As New DataTable("Charges")

    Public Sub New(ByVal VisitId As Integer)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.VisitId = VisitId
    End Sub

    Private Sub frmNurseNote_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False

                PopulateLookupDX(lkHeightUnit, "LengthUnits", "LengthId", "LtblUnitsLength", "LengthId,LengthUnits", "", "LengthUnits")
                PopulateLookupDX(lkGirthUnit, "LengthUnits", "LengthId", "LtblUnitsLength", "LengthId,LengthUnits", "", "LengthUnits")
                PopulateLookupDX(lkWeightUnit, "WeightUnit", "WeightId", "LtblUnitsWeight", "WeightId,WeightUnit", "", "WeightUnit")
                PopulateLookupDX(lkTemperatureUnit, "TempUnit", "TempUnitId", "LtblUnitsTemp", "TempUnitId,TempUnit", "", "TempUnit")
                PopulateLookupDX(lkBloodSugarUnit, "BloodSugarUnit", "BloodSugarID", "LtblUnitsBloodSugar", "BloodSugarID,BloodSugarUnit", "", "BloodSugarUnit")
                'Populate Item
                Call PopulateGridLookupDX(lkItem, "ItemName", "ItemId", "tblItem", "ItemId,ItemCode,ItemName,(Case When IsBillable=0 then 'No' When IsBillable=1 then 'Yes' End) [Billable],(Case When IsBillable=0 then 0 When IsBillable=1 then ChargeToPatient End)  [Charge],QOH", , "ItemName", , , 500)
                'lkHeightUnit.ItemIndex = 0
                'lkGirthUnit.ItemIndex = 0
                'lkWeightUnit.ItemIndex = 0
                'lkTemperatureUnit.ItemIndex = 0
                'lkBloodSugarUnit.ItemIndex = 0
                txtVisualAcuityLeftD.Text = 20
                txtVisualAcuityRightD.Text = 20

                Call btnCancelItems_Click(Nothing, Nothing)

                Call DisplayCharges(0)

                Dim dsTemp As DataSet = FillDataSet("SELECT tblPatientInfo.PatientTitle + ' ' + (IsNull(tblPatientInfo.LastName + ', ' , '') + tblPatientInfo.FirstName + Isnull(' ' + tblPatientInfo.MiddleName, '') ) [Name], tblVisits.VisitDate [VisitDate] FROM  tblPatientInfo INNER JOIN  tblVisits ON tblPatientInfo.PatientId = tblVisits.PatientId  WHERE  tblVisits.VisitId = " & VisitId)
                Dim strText As String = ""
                If dsTemp.Tables(0).Rows.Count > 0 Then
                    strText = Format(dsTemp.Tables(0).Rows(0).Item("VisitDate"), gstrDtFormat & " hh:mm tt")
                    strText = dsTemp.Tables(0).Rows(0).Item("Name") & "(" & strText & ")"
                End If
                Me.Text = strText
                Call DisplayData()
                txtBloodSupineS.Focus()
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmNurseNote_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try

            Dim intUnload As DialogResult

            If mblnChanged = True Then
                intUnload = MessageBox.Show("Is NURSE's visit complete?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.No Then
                    'e.Cancel = True
                    Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    blnUnload = True
                    If blnSaveRecords() = False Then
                        e.Cancel = True
                        blnUnload = False
                        Exit Sub
                    End If
                    mblnChanged = False
                End If
            End If
            blnUnload = False

        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmNurseNote_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call GetAccessPermission(Me, "frmNurseNote")
            Call InitializedDataEntry()
            ChangeStatus(VisitId, PatientStatus.WithNurse)
            mblnActivate = True
            mblnChanged = True

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub DisplayData()
        'Display data in form fields.
        Dim dsTemp As DataSet
        Dim strQuery As String
        Try
            'Initial entry
            'Fill Physical Measurement groupbox
            mstrMode = "Add"
            strQuery = "SELECT * FROM tblVisitGeneralAssessment WHERE VisitId = " & VisitId
            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    txtHeight.EditValue = IIf(Val(.Rows(0).Item("Height") & "") = 0, DBNull.Value, Val(.Rows(0).Item("Height") & ""))
                    lkHeightUnit.EditValue = .Rows(0).Item("HeightUnitsId")
                    txtWeight.EditValue = IIf(Val(.Rows(0).Item("Weight") & "") = 0, DBNull.Value, Val(.Rows(0).Item("Weight") & ""))
                    lkWeightUnit.EditValue = .Rows(0).Item("WeightUnitsId")
                    txtAbdominalGirth.EditValue = IIf(Val(.Rows(0).Item("AbdominalGirth") & "") = 0, DBNull.Value, Val(.Rows(0).Item("AbdominalGirth") & ""))
                    lkGirthUnit.EditValue = .Rows(0).Item("AbdominalGirthUnitsId")
                    txtTemperature.EditValue = IIf(Val(.Rows(0).Item("Temperature") & "") = 0, DBNull.Value, Val(.Rows(0).Item("Temperature") & ""))
                    lkTemperatureUnit.EditValue = .Rows(0).Item("TemperatureUnits")
                    mstrMode = "Edit"
                End If
            End With

            'dsTemp.Dispose()

            'Fill bloob sugar in Measurement groupbox
            strQuery = "SELECT * FROM tblVisitGenitoUrinary WHERE VisitId = " & VisitId
            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    txtBloodSugar.EditValue = IIf(Val(.Rows(0).Item("BloodSugar") & "") = 0, DBNull.Value, Val(.Rows(0).Item("BloodSugar") & ""))
                    If IsDBNullOrNothing(.Rows(0).Item("BloodSugarUnit")) Then
                        lkBloodSugarUnit.EditValue = Nothing
                    Else
                        lkBloodSugarUnit.EditValue = .Rows(0).Item("BloodSugarUnit")
                    End If
                    If IsDBNullOrNothing(.Rows(0).Item("Urine")) Then
                        txtUrine.Text = Nothing
                    Else
                        txtUrine.Text = .Rows(0).Item("Urine")
                    End If
                    mstrMode = "Edit"
                End If
            End With

            'dsTemp.Dispose()

            'Fill Blood pressure and pulse groupbox
            strQuery = "SELECT * FROM tblVisitBPPulse WHERE VisitId = " & VisitId
            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    txtBloodSupineS.EditValue = IIf(Val(.Rows(0).Item("BPSupineS") & "") = 0, DBNull.Value, Val(.Rows(0).Item("BPSupineS") & ""))
                    txtBloodSupineD.EditValue = IIf(Val(.Rows(0).Item("BPSupineD") & "") = 0, DBNull.Value, Val(.Rows(0).Item("BPSupineD") & ""))
                    txtBloodSittingS.EditValue = IIf(Val(.Rows(0).Item("BPSittingS") & "") = 0, DBNull.Value, Val(.Rows(0).Item("BPSittingS") & ""))
                    txtBloodSittingD.EditValue = IIf(Val(.Rows(0).Item("BPSittingD") & "") = 0, DBNull.Value, Val(.Rows(0).Item("BPSittingD") & ""))
                    txtBloodStandingS.EditValue = IIf(Val(.Rows(0).Item("BPStandingS") & "") = 0, DBNull.Value, Val(.Rows(0).Item("BPStandingS") & ""))
                    txtBloodStandingD.EditValue = IIf(Val(.Rows(0).Item("BPStandingD") & "") = 0, DBNull.Value, Val(.Rows(0).Item("BPStandingD") & ""))
                    txtPulse.EditValue = IIf(Val(.Rows(0).Item("Pulse") & "") = 0, DBNull.Value, Val(.Rows(0).Item("Pulse") & ""))
                    txtPulseExcercise.EditValue = IIf(Val(.Rows(0).Item("PulseExcercise") & "") = 0, DBNull.Value, Val(.Rows(0).Item("PulseExcercise") & ""))
                    txtPulsePostExcercise.EditValue = IIf(Val(.Rows(0).Item("PulsePostExcercise") & "") = 0, DBNull.Value, Val(.Rows(0).Item("PulsePostExcercise") & ""))
                    mstrMode = "Edit"
                End If
            End With

            'dsTemp.Dispose()


            'Fill Visual acuity groupbox
            strQuery = "SELECT * FROM tblVisualAcuity WHERE VisitId = " & VisitId
            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    txtVisualAcuityRightS.EditValue = .Rows(0).Item("VisualAcuityRight") & ""
                    txtVisualAcuityLeftS.EditValue = .Rows(0).Item("VisualAcuityLeft") & ""
                    txtVisualAcuityRightD.EditValue = .Rows(0).Item("VisualAcuityRight1") & ""
                    txtVisualAcuityLeftD.EditValue = .Rows(0).Item("VisualAcuityLeft1") & ""
                    mstrMode = "Edit"
                End If
            End With

            'dsTemp.Dispose()

            'Fill respiratory text
            strQuery = "SELECT * FROM tblVisitRespiratory WHERE VisitId = " & VisitId
            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    txtRespiratory.EditValue = IIf(Val(.Rows(0).Item("RespiratoryRate") & "") = 0, DBNull.Value, Val(.Rows(0).Item("RespiratoryRate") & ""))
                    mstrMode = "Edit"
                End If
            End With

            dsTemp.Dispose()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Function IsValidEntry() As Boolean
        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsValidEntry = False

        If IsDBNullOrNothing(txtHeight.Text) = False And IsDBNullOrNothing(lkHeightUnit.EditValue) Then
            strMsg = "Please select Height unit."
            lkHeightUnit.Focus()
        ElseIf IsDBNullOrNothing(txtWeight.Text) = False And IsDBNullOrNothing(lkWeightUnit.Text) Then
            strMsg = "Please select Weight unit."
            lkWeightUnit.Focus()
        ElseIf IsDBNullOrNothing(txtAbdominalGirth.Text) = False And IsDBNullOrNothing(lkGirthUnit.EditValue) Then
            strMsg = "Please select Abdominal Girth unit."
            lkGirthUnit.Focus()
        ElseIf IsDBNullOrNothing(txtTemperature.Text) = False And IsDBNullOrNothing(lkTemperatureUnit.Text) Then
            strMsg = "Please select Temperature unit."
            lkTemperatureUnit.Focus()
        ElseIf IsDBNullOrNothing(txtBloodSugar.Text) = False And IsDBNullOrNothing(lkBloodSugarUnit.Text) Then
            strMsg = "Please select Blood Sugar unit."
            lkBloodSugarUnit.Focus()
        End If

        If Trim(strMsg) <> "" Then
            IsValidEntry = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsValidEntry = True
        End If
    End Function

    Private Function blnSaveRecords() As Boolean
        Dim blnIsTransactionOpen As Boolean
        Dim strQuery As String, strFeilds As String, strRowCount As String

        Try
            blnSaveRecords = False

            If IsValidEntry() = False Then
                Exit Function
            End If

            If (blnUnload = False) Then
                If (MessageBox.Show("Are you sure to " & IIf(mstrMode = "Add", "add", "modify") & " Nurse's notes?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                    txtBloodSupineS.Focus()
                    Exit Function
                End If
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            strRowCount = strRecordID("tblVisitGeneralAssessment", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitGeneralAssessment(VisitId,Height,HeightUnitsId,Weight,WeightUnitsId,AbdominalGirth,AbdominalGirthUnitsId,Temperature,TemperatureUnits) "

                strQuery = VisitId
                If IsDBNullOrNothing(txtHeight.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtHeight.EditValue)
                End If
                If IsDBNullOrNothing(lkHeightUnit.EditValue) Then
                    strQuery = strQuery & ", Null"
                Else
                    strQuery = strQuery & ", " & Val(lkHeightUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtWeight.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & ", " & Val(txtWeight.EditValue)
                End If
                If IsDBNullOrNothing(lkWeightUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(lkWeightUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtAbdominalGirth.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtAbdominalGirth.EditValue)
                End If
                If IsDBNullOrNothing(lkGirthUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(lkGirthUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtTemperature.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtTemperature.EditValue)
                End If
                If IsDBNullOrNothing(lkTemperatureUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(lkTemperatureUnit.EditValue)
                End If


                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "VisitId=" & VisitId
                If IsDBNullOrNothing(txtHeight.Text) Then
                    strQuery = strQuery & ",Height=Null"
                Else
                    strQuery = strQuery & ",Height=" & Val(txtHeight.EditValue & "")
                End If
                If IsDBNullOrNothing(lkHeightUnit.EditValue) Then
                    strQuery = strQuery & ",HeightUnitsId=Null"
                Else
                    strQuery = strQuery & ",HeightUnitsId=" & lkHeightUnit.EditValue
                End If
                If IsDBNullOrNothing(txtWeight.Text) Then
                    strQuery = strQuery & ",Weight=Null"
                Else
                    strQuery = strQuery & ",Weight=" & Val(txtWeight.EditValue & "")
                End If
                If IsDBNullOrNothing(lkWeightUnit.EditValue) Then
                    strQuery = strQuery & ",WeightUnitsId=Null"
                Else
                    strQuery = strQuery & ",WeightUnitsId=" & lkWeightUnit.EditValue
                End If
                If IsDBNullOrNothing(txtAbdominalGirth.Text) Then
                    strQuery = strQuery & ",AbdominalGirth=Null"
                Else
                    strQuery = strQuery & ",AbdominalGirth=" & Val(txtAbdominalGirth.EditValue & "")
                End If
                If IsDBNullOrNothing(lkGirthUnit.EditValue) Then
                    strQuery = strQuery & ",AbdominalGirthUnitsId=Null"
                Else
                    strQuery = strQuery & ",AbdominalGirthUnitsId=" & lkGirthUnit.EditValue
                End If
                If IsDBNullOrNothing(txtTemperature.Text) Then
                    strQuery = strQuery & ",Temperature=Null"
                Else
                    strQuery = strQuery & ",Temperature=" & Val(txtTemperature.EditValue & "")
                End If
                If IsDBNullOrNothing(lkTemperatureUnit.EditValue) Then
                    strQuery = strQuery & ",TemperatureUnits=Null"
                Else
                    strQuery = strQuery & ",TemperatureUnits=" & lkTemperatureUnit.EditValue
                End If


                Call UpdateTable("tblVisitGeneralAssessment", strQuery, " VisitId=" & VisitId)
            End If

            strRowCount = strRecordID("tblVisitGenitoUrinary", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitGenitoUrinary(VisitId,BloodSugar,BloodSugarUnit,Urine) "
                strQuery = VisitId & "," & Val(txtBloodSugar.EditValue & "") & ", " & Val(lkBloodSugarUnit.EditValue)
                If IsDBNullOrNothing(txtUrine.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Trim(SmartReplace(txtUrine.Text) & "")
                End If

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "BloodSugar=" & Val(txtBloodSugar.EditValue & "")
                strQuery = strQuery & ",BloodSugarUnit=" & Val(lkBloodSugarUnit.EditValue)
                If IsDBNullOrNothing(txtUrine.Text) Then
                    strQuery = strQuery & ",Urine=Null"
                Else
                    strQuery = strQuery & ",Urine=" & Trim(SmartReplace(txtUrine.Text) & "")
                End If

                Call UpdateTable("tblVisitGenitoUrinary", strQuery, " VisitId=" & VisitId)
            End If

            strRowCount = strRecordID("tblVisitBPPulse", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then

                strFeilds = " tblVisitBPPulse(VisitId,BPSupineS,BPSupineD,BPSittingS,BPSittingD,BPStandingS,BPStandingD,Pulse,PulseExcercise,PulsePostExcercise)"
                strQuery = VisitId
                strQuery = strQuery & "," & Val(txtBloodSupineS.EditValue & "")
                strQuery = strQuery & "," & Val(txtBloodSupineD.EditValue & "")
                strQuery = strQuery & "," & Val(txtBloodSittingS.EditValue & "")
                strQuery = strQuery & "," & Val(txtBloodSittingD.EditValue & "")
                strQuery = strQuery & "," & Val(txtBloodStandingS.EditValue & "")
                strQuery = strQuery & "," & Val(txtBloodStandingD.EditValue & "")
                strQuery = strQuery & "," & Val(txtPulse.EditValue & "")
                strQuery = strQuery & "," & Val(txtPulseExcercise.EditValue & "")
                strQuery = strQuery & "," & Val(txtPulseExcercise.EditValue & "")

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = " VisitId=" & VisitId
                strQuery = strQuery & ",BPSupineS=" & Val(txtBloodSupineS.EditValue & "")
                strQuery = strQuery & ",BPSupineD=" & Val(txtBloodSupineD.EditValue & "")
                strQuery = strQuery & ",BPSittingS=" & Val(txtBloodSittingS.EditValue & "")
                strQuery = strQuery & ",BPSittingD=" & Val(txtBloodSittingD.EditValue & "")
                strQuery = strQuery & ",BPStandingS=" & Val(txtBloodStandingS.EditValue & "")
                strQuery = strQuery & ",BPStandingD=" & Val(txtBloodStandingD.EditValue & "")
                strQuery = strQuery & ",Pulse=" & Val(txtPulse.EditValue & "")
                strQuery = strQuery & ",PulseExcercise=" & Val(txtPulseExcercise.EditValue & "")
                strQuery = strQuery & ",PulsePostExcercise=" & Val(txtPulsePostExcercise.EditValue & "")

                Call UpdateTable("tblVisitBPPulse", strQuery, " VisitId=" & VisitId)
            End If

            strRowCount = strRecordID("tblVisualAcuity", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisualAcuity(VisitId,VisualAcuityRight,VisualAcuityLeft,VisualAcuityRight1,VisualAcuityLeft1)"
                strQuery = VisitId & "," & SmartReplace(txtVisualAcuityRightS.EditValue) & "," & SmartReplace(txtVisualAcuityLeftS.EditValue) & "," & SmartReplace(txtVisualAcuityRightD.EditValue) & "," & SmartReplace(txtVisualAcuityLeftD.EditValue)

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "VisitId=" & VisitId
                strQuery = strQuery & ",VisualAcuityRight=" & SmartReplace(txtVisualAcuityRightS.EditValue)
                strQuery = strQuery & ",VisualAcuityLeft=" & SmartReplace(txtVisualAcuityLeftS.EditValue)
                strQuery = strQuery & ",VisualAcuityRight1=" & SmartReplace(txtVisualAcuityRightD.EditValue)
                strQuery = strQuery & ",VisualAcuityLeft1=" & SmartReplace(txtVisualAcuityLeftD.EditValue)
                Call UpdateTable("tblVisualAcuity", strQuery, " VisitId=" & VisitId)
            End If
            strRowCount = strRecordID("tblVisitRespiratory", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitRespiratory(VisitId,RespiratoryRate)"
                strQuery = VisitId & "," & Val(txtRespiratory.EditValue)

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "VisitId=" & VisitId & ",RespiratoryRate=" & Val(txtRespiratory.EditValue & "")

                Call UpdateTable("tblVisitRespiratory", strQuery, " VisitId=" & VisitId)
            End If

            blnSaveRecords = True

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
            mblnChanged = False
            'MessageBox.Show("Nurse's notes saved.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)

            ChangeStatus(VisitId, PatientStatus.AwaitingDoctor)

        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Function

    Public Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            If mblnChanged = False Then Exit Sub
            If blnSaveRecords() = False Then Exit Sub
            gblnIsRefreshed = True
            Me.Close()

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub txtBloodSupineS_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _
    txtBloodSupineS.EditValueChanged, txtBloodSupineD.EditValueChanged, txtBloodStandingS.EditValueChanged, _
    txtBloodStandingD.EditValueChanged, txtBloodSittingS.EditValueChanged, txtBloodSittingD.EditValueChanged, _
    txtWeight.EditValueChanged, txtVisualAcuityRightS.EditValueChanged, txtVisualAcuityLeftS.EditValueChanged, _
    txtTemperature.EditValueChanged, txtRespiratory.EditValueChanged, txtPulsePostExcercise.EditValueChanged, _
    txtPulseExcercise.EditValueChanged, txtPulse.EditValueChanged, txtHeight.EditValueChanged, txtBloodSugar.EditValueChanged, txtAbdominalGirth.EditValueChanged, _
    lkWeightUnit.EditValueChanged, lkTemperatureUnit.EditValueChanged, lkHeightUnit.EditValueChanged, lkGirthUnit.EditValueChanged, lkBloodSugarUnit.EditValueChanged, txtVisualAcuityLeftD.EditValueChanged, txtVisualAcuityRightD.EditValueChanged
        mblnChanged = True
    End Sub

    'Private Sub txtBloodSupineS_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtWeight.KeyPress, txtTemperature.KeyPress, txtRespiratory.KeyPress, txtPulsePostExcercise.KeyPress, txtPulseExcercise.KeyPress, txtPulse.KeyPress, txtHeight.KeyPress, txtBloodSupineS.KeyPress, txtBloodSupineD.KeyPress, txtBloodSugar.KeyPress, txtBloodStandingS.KeyPress, txtBloodStandingD.KeyPress, txtBloodSittingS.KeyPress, txtBloodSittingD.KeyPress, txtAbdominalGirth.KeyPress
    '    If IsNumeric(e.KeyChar) = False AndAlso Asc(e.KeyChar) <> Keys.Back Then
    '        e.Handled = True
    '    End If
    'End Sub

    Private Sub btnUrineSampleReadings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUrineSampleReadings.Click
        Cursor.Current = Cursors.WaitCursor
        Dim UrineTestForm As New frmUrineTest(VisitId)
        'UrineTestForm.ShowInTaskbar = False
        'UrineTestForm.Location = New Point(Me.Location.X + 255, Me.Location.Y + 40)
        UrineTestForm.ShowInTaskbar = False
        UrineTestForm.ShowDialog()
        Cursor.Current = Cursors.Default
    End Sub

    Private Sub txtBloodSupineS_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBloodSupineS.TextChanged, txtWeight.TextChanged, txtVisualAcuityRightS.TextChanged, txtVisualAcuityLeftS.TextChanged, txtTemperature.TextChanged, txtRespiratory.TextChanged, txtPulsePostExcercise.TextChanged, txtPulseExcercise.TextChanged, txtPulse.TextChanged, txtHeight.TextChanged, txtBloodSupineD.TextChanged, txtBloodSugar.TextChanged, txtBloodStandingS.TextChanged, txtBloodStandingD.TextChanged, txtBloodSittingS.TextChanged, txtBloodSittingD.TextChanged, txtAbdominalGirth.TextChanged, lkWeightUnit.TextChanged, lkTemperatureUnit.TextChanged, lkHeightUnit.TextChanged, lkGirthUnit.TextChanged, lkBloodSugarUnit.TextChanged
        mblnChanged = True
    End Sub

    Private Sub InitializedDataEntry()
        Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)

        With dtCharge.Columns
            .Add("Date", GetType(Date))
            .Add("Procedure", GetType(String))
            .Add("Quantity", GetType(Integer))
            .Add("Cost", GetType(Decimal))
            .Add("Charge Amount", GetType(Decimal))
            .Add("ProcedureTypeId", GetType(Integer))
            .Add("ID", GetType(Integer))
            .Add("VisitId", GetType(Integer))
            .Add("Type", GetType(String))
        End With
        grdCharges.DataSource = dtCharge

        With gdvCharges
            .Columns("Date").AppearanceHeader.Font = fnBold
            .Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
            .Columns("Date").DisplayFormat.FormatString = gstrDtFormat & " hh:mm tt"
            .Columns("Procedure").AppearanceHeader.Font = fnBold
            .Columns("Quantity").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Quantity").AppearanceHeader.Font = fnBold
            .Columns("Quantity").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Quantity").DisplayFormat.FormatString = "0"
            .Columns("Cost").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Cost").AppearanceHeader.Font = fnBold
            .Columns("Cost").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Cost").DisplayFormat.FormatString = "0.00"
            .Columns("Cost").Caption = "Price"
            .Columns("Charge Amount").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Charge Amount").AppearanceHeader.Font = fnBold
            .Columns("Charge Amount").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Charge Amount").DisplayFormat.FormatString = "0.00"
            .Columns("Charge Amount").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
            .Columns("ProcedureTypeId").Visible = False
            .Columns("ProcedureTypeId").OptionsColumn.ShowInCustomizationForm = False
            .Columns("ID").Visible = False
            .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
            .Columns("Type").Visible = False
            .Columns("Type").OptionsColumn.ShowInCustomizationForm = False
            .Columns("VisitId").Visible = False
            .Columns("VisitId").OptionsColumn.ShowInCustomizationForm = False
            .OptionsView.ColumnAutoWidth = True
            .OptionsBehavior.Editable = False
        End With

    End Sub

    Private Sub PopulateChargesInGrid()
        Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
        Dim DoctorCriteria As String
        If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
            DoctorCriteria = " AND tblVisits.PracticeId=" & GetPracticeId(gintUserID) & " "
        Else
            DoctorCriteria = ""
        End If

        Dim strQuery As String = "SELECT VisitDate [Date],ItemName[Procedure],Quantity," & _
                                "IsNull(ChargeToPatient,0) AS Cost,Quantity * Isnull(ChargeToPatient,0)  [Charge Amount],tblInventoryIssue.ItemId [ProcedureTypeId],IssueId [ID],tblInventoryIssue.VisitId,[Type]='Inventory'" & _
                                " FROM tblInventoryIssue JOIN tblItem ON tblInventoryIssue.ItemId=tblItem.ItemId" & _
                                " JOIN  tblVisits ON tblVisits.VisitId=tblInventoryIssue.VisitId" & _
                                " WHERE tblVisits.VisitId = " & VisitId & DoctorCriteria
        Dim dsTemp As DataSet = FillDataSet(strQuery)

        With grdCharges
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With

        With gdvCharges
            .Columns("Date").AppearanceHeader.Font = fnBold
            .Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
            .Columns("Date").DisplayFormat.FormatString = gstrDtFormat & " hh:mm tt"
            .Columns("Procedure").AppearanceHeader.Font = fnBold
            .Columns("Quantity").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Quantity").AppearanceHeader.Font = fnBold
            .Columns("Quantity").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Quantity").DisplayFormat.FormatString = "0"
            .Columns("Cost").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Cost").AppearanceHeader.Font = fnBold
            .Columns("Cost").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Cost").DisplayFormat.FormatString = "0.00"
            .Columns("Cost").Caption = "Price"
            .Columns("Charge Amount").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Charge Amount").AppearanceHeader.Font = fnBold
            .Columns("Charge Amount").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Charge Amount").DisplayFormat.FormatString = "0.00"
            .Columns("Charge Amount").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
            .Columns("ProcedureTypeId").Visible = False
            .Columns("ProcedureTypeId").OptionsColumn.ShowInCustomizationForm = False
            .Columns("ID").Visible = False
            .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
            .Columns("Type").Visible = False
            .Columns("Type").OptionsColumn.ShowInCustomizationForm = False
            .Columns("VisitId").Visible = False
            .Columns("VisitId").OptionsColumn.ShowInCustomizationForm = False
            .OptionsView.ColumnAutoWidth = True
            .OptionsBehavior.Editable = False
        End With
    End Sub

    Private Sub EnableDisableControls(ByVal blnEnable As Boolean)
        If blnAdd = True Then
            btnAddItems.Enabled = blnEnable
        Else
            btnAddItems.Enabled = False
        End If
        If blnEdit = True Then
            btnUpdateItems.Enabled = blnEnable
        Else
            btnUpdateItems.Enabled = False
        End If
        If blnDelete = True Then
            btnDeleteItems.Enabled = blnEnable
        Else
            btnDeleteItems.Enabled = False
        End If
        If gdvCharges.RowCount = 0 Then
            btnUpdateItems.Enabled = False : btnDeleteItems.Enabled = False
        End If
    End Sub


    Private Function IsInventoryBoxValid() As Boolean
        If IsDBNullOrNothing(lkItem.EditValue) = True Then
            MessageBox.Show("Please select Item.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            lkItem.Focus()
            Return False
        End If

        If txtItemQuantity.EditValue <= 0 Then
            MessageBox.Show("Please enter Quantity.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtItemQuantity.Focus()
            Return False
        End If

        If Not IsNumeric(txtItemQuantity.EditValue) Then
            MessageBox.Show("Please enter Quantity in number.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtItemQuantity.Focus()
            txtItemQuantity.SelectAll()
            Return False
        End If

        Return True
    End Function

    Private Sub btnAddItems_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddItems.Click
        Try
            If btnAddItems.Text = "&N" Then
                btnAddItems.Text = "&A"
                lkItem.EditValue = DBNull.Value
                txtItemQuantity.EditValue = "1"
                txtItemCharge.Text = ""
                btnUpdateItems.Enabled = False
                btnDeleteItems.Enabled = False
                lkItem.Focus()
            Else
                If IsInventoryBoxValid() = False Then    'check if user has entered values in textbox
                    Exit Sub
                End If



                LoadCursor(Me)
                Dim strQuery As String
                strQuery = lngAutogeneratePrimaryKey("tblInventoryIssue", "IssueId") & _
                            " , " & VisitId & _
                            " , " & lkItem.EditValue & _
                            " , " & txtItemQuantity.EditValue & _
                            " , 1" & _
                            " , " & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt"))
                Call InsertintoTable("tblInventoryIssue", strQuery)
                Call PopulateChargesInGrid()
                Dim Qoh As Integer = Val(strRecordID("tblItem", "QOH", "ItemId=" & lkItem.EditValue))
                If Qoh < 0 Then
                    MessageBox.Show("After this transaction the stock of " & lkItem.Text & " will be negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End If
                gdvCharges.MoveLast()
                btnAddItems.Text = "&N"
            End If
        Catch ex As Exception
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        Finally
            Call EnableDisableControls(True)
            DestroyCrushor(Me)
        End Try
    End Sub


    Private Sub btnUpdateItems_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateItems.Click
        Try
            Dim strQuery As String
            If IsInventoryBoxValid() = False Then    'check if user has entered values in textbox
                Exit Sub
            End If
            strQuery = "ItemId=" & lkItem.EditValue & _
                        ",Quantity=" & txtItemQuantity.EditValue & _
                        ",LastModified=" & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt"))
            Call UpdateTable("tblInventoryIssue", strQuery, "IssueId=" & gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "ID"))
            Dim intHandel As Integer = gdvCharges.FocusedRowHandle
            Call PopulateChargesInGrid()
            Dim Qoh As Integer = Val(strRecordID("tblItem", "QOH", "ItemId=" & lkItem.EditValue))
            If Qoh < 0 Then
                MessageBox.Show("After this transaction the stock of " & lkItem.Text & " will be negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
            gdvCharges.FocusedRowHandle = intHandel
            'MessageBox.Show("Charges updated.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        Finally
            Call EnableDisableControls(True)
            DestroyCrushor(Me)
        End Try
    End Sub

    Private Sub btnDeleteItems_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDeleteItems.Click
        Try
            If MessageBox.Show("Do you want to delete this Item details?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
                Exit Sub
            Else
                Call DeleteFromTable("tblInventoryIssue", "IssueId=" & gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "ID"))
                Call PopulateChargesInGrid()
                Dim Qoh As Integer = Val(strRecordID("tblItem", "QOH", "ItemId=" & lkItem.EditValue))
                If Qoh < 0 Then
                    MessageBox.Show("After this transaction the stock of " & lkItem.Text & " will be negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End If
            End If
        Catch ex As Exception
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        End Try
    End Sub

    Private Sub btnCancelItems_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelItems.Click
        Call PopulateChargesInGrid()
        If gdvCharges.RowCount > 0 Then
            btnAddItems.Text = "&N"
            Call EnableDisableControls(True)
        Else
            lkItem.EditValue = DBNull.Value
            txtItemQuantity.EditValue = "0"
            txtItemCharge.Text = ""
            btnAddItems.Text = "&A"
            lkItem.Focus()
        End If
    End Sub

    Private Sub gdvCharges_FocusedRowChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvCharges.FocusedRowChanged
        Try
            Call DisplayCharges(gdvCharges.FocusedRowHandle)
            lkItem.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
        End Try
    End Sub

    Private Sub DisplayCharges(ByVal intRowhandel As Integer)
        Dim dr As DataRow = dtCharge.NewRow()
        dr = gdvCharges.GetDataRow(intRowhandel)
        If IsDBNullOrNothing(dr) = False Then
            
            lkItem.EditValue = dr.Item("ProcedureTypeId")
            txtItemQuantity.EditValue = dr.Item("Quantity")
            txtItemCharge.EditValue = dr.Item("Cost")

        End If
    End Sub

    Private Sub gdvCharges_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvCharges.RowCountChanged
        If gdvCharges.RowCount > 0 Then
            btnAddItems.Text = "&N"
            Call EnableDisableControls(True)
        Else
            btnAddItems.Text = "&A"
            btnUpdateItems.Enabled = False
            btnDeleteItems.Enabled = False
        End If
    End Sub

    Private Sub lkItem_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkItem.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateGridLookupDX(lkItem, "ItemName", "ItemId", "tblItem", "ItemId,ItemCode,ItemName,(Case When IsBillable=0 then 'No' When IsBillable=1 then 'Yes' End) [Billable],(Case When IsBillable=0 then 0 When IsBillable=1 then ChargeToPatient End)  [Charge],QOH", , "ItemName", , , 500)
        End If
    End Sub

    Private Sub lkItem_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkItem.EditValueChanged
        Dim ItemDetailsDataRow As DataRow
        ItemDetailsDataRow = CType(lkItem.Properties.View.GetDataRow(lkItem.Properties.View.FocusedRowHandle), DataRow)
        If IsDBNullOrNothing(ItemDetailsDataRow) Then Exit Sub
        If IsDBNullOrNothing(ItemDetailsDataRow.Item("Charge")) = False Then
            txtItemCharge.Text = ItemDetailsDataRow.Item("Charge")
        Else
            txtItemCharge.Text = Nothing
        End If
    End Sub

    Private Sub btnAddItems_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles btnAddItems.MouseMove
        If btnAddItems.Text = "&A" Then
            btnAddItems.ToolTip = "Add"
        ElseIf btnAddItems.Text = "&N" Then
            btnAddItems.ToolTip = "New"
        End If
    End Sub
End Class
